package com.qiaomeng.flutter.baichuan.handlers;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.MainThread;

import com.alibaba.alibclogin.AlibcLogin;
import com.alibaba.alibcprotocol.callback.AlibcLoginCallback;
import com.alibaba.alibcprotocol.param.AlibcBizParams;
import com.alibaba.alibcprotocol.param.AlibcDegradeType;
import com.alibaba.alibcprotocol.param.AlibcShowParams;
import com.alibaba.alibcprotocol.param.AlibcTaokeParams;
import com.alibaba.alibcprotocol.param.OpenType;
import com.alibaba.alibctriver.AlibcImageCenter;
import com.alibaba.alibctriver.AlibcNavigateCenter;
import com.alibaba.baichuan.trade.common.AlibcTradeCommon;
import com.baichuan.nb_trade.AlibcTrade;
import com.baichuan.nb_trade.callback.AlibcTradeCallback;
import com.baichuan.nb_trade.callback.AlibcTradeInitCallback;
import com.baichuan.nb_trade.core.AlibcTradeBiz;
import com.baichuan.nb_trade.core.AlibcTradeSDK;
import com.facebook.drawee.backends.pipeline.Fresco;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodChannel;

public class BCApiHandler {
    private static String TAG = "BCApiHandler";
    private Activity context;
    private MethodChannel channel;

    public BCApiHandler(Activity context, MethodChannel channel) {
        this.context = context;
        this.channel = channel;
        Fresco.initialize(context);
        AlibcTradeCommon.turnOffDebug();
        AlibcTradeBiz.turnOffDebug();
        AlibcTradeCommon.closeErrorLog();
    }

    /**
     * 开启调试模式
     */
    public void debug() {
        AlibcTradeCommon.turnOnDebug();
        AlibcTradeCommon.openErrorLog();
        AlibcTradeBiz.turnOnDebug();
    }


    /**
     * 初始化
     *
     * @param result
     */
    public void asyncInit(final MethodChannel.Result result) {
        // 初始化扩展map（默认可传入空）
        Map<String, Object> params = new HashMap<>();
        params.put("open4GDownload", true);
        AlibcTradeSDK.asyncInit(context.getApplication(), params, new AlibcTradeInitCallback() {
            @Override
            public void onSuccess() {
                Map map = new HashMap();
                map.put("status", true);
                map.put("msg", "SDK初始化成功");
                result.success(map);

            }

            @Override
            public void onFailure(int i, String s) {
                Map map = new HashMap();
                map.put("status", false);
                map.put("msg", s);
                map.put("code", i);
                result.success(map);
            }
        });
    }


    /**
     * 设置三方媒体应用版本号
     *
     * @param v
     */
    public void setIsvVersion(String v) {
        AlibcTradeCommon.setIsvVersion(v);
    }

    /**
     * 打开登录
     *
     * @param result
     */
    public void showLogin(final MethodChannel.Result result) {
        AlibcLogin.getInstance().showLogin(new AlibcLoginCallback() {
            @Override
            public void onSuccess(String userId, String userNick) {
                Map map = new HashMap();
                map.put("status", true);
                map.put("msg", "登录成功");
                map.put("userInfo", AlibcLogin.getInstance().getUserInfo());
                result.success(map);
            }

            @Override
            public void onFailure(int i, String s) {
                Map map = new HashMap();
                map.put("status", false);
                map.put("msg", s);
                map.put("code", i);
                result.success(map);
            }
        });
    }

    /**
     * 登出
     *
     * @param result
     */
    public void logout(final MethodChannel.Result result) {
        AlibcLogin.getInstance().logout(new AlibcLoginCallback() {
            @Override
            public void onSuccess(String userId, String userNick) {
                Map map = new HashMap();
                map.put("status", true);
                map.put("msg", "登出成功");
                map.put("userInfo", AlibcLogin.getInstance().getUserInfo());
                result.success(map);
            }

            @Override
            public void onFailure(int i, String s) {
                Map map = new HashMap();
                map.put("status", false);
                map.put("msg", s);
                map.put("code", i);
                result.success(map);
            }
        });
    }

    /**
     * 判断是否登录淘宝
     *
     * @param result
     */
    public void isLogin(MethodChannel.Result result) {
        Map map = new HashMap();
        map.put("status", false);
        map.put("msg", "淘宝未登录");
        map.put("isLogin", AlibcLogin.getInstance().isLogin());
        result.success(map);
    }


    /**
     * 获取淘宝用户信息
     *
     * @param result
     */
    public void getUserInfo(MethodChannel.Result result) {
        if (AlibcLogin.getInstance().isLogin()) {
            Map map = new HashMap();
            map.put("status", true);
            map.put("msg", "获取成功");
            map.put("userInfo", AlibcLogin.getInstance().getUserInfo());
            result.success(map);
        } else {
            Map map = new HashMap();
            map.put("status", false);
            map.put("msg", "淘宝未登录");
        }

    }


    /**
     * 打开电商套件页面
     *
     * @param suiteCode   套件code
     * @param bizParams   业务参数
     * @param showParams  页面打开方式自定义参数
     * @param taokeParams 淘客参数
     * @param trackParams 链路跟踪参数（自定义）
     */
    public void openByCode(
            String suiteCode,
            Map<String, Object> bizParams,
            Map<String, String> showParams,
            Map<String, Object> taokeParams,
            Map<String, String> trackParams,
            final MethodChannel.Result result) {

        AlibcTrade.openByCode(
                context,
                suiteCode,
                mapToAlibcBizParams(bizParams),
                mapToAlibcShowParams(showParams),
                mapToAlibcTaokeParams(taokeParams),
                trackParams,
                new AlibcTradeCallback() {
                    @Override
                    public void onSuccess(int i) {
                        Map map = new HashMap();
                        map.put("status", true);
                        map.put("code", i);
                        map.put("msg", "打开成功");
                        result.success(map);
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Map map = new HashMap();
                        map.put("status", false);
                        map.put("msg", s);
                        map.put("code", i);
                        result.success(map);
                    }
                });
    }

    /**
     * 打开普通电商页面
     *
     * @param detailUrl   目标打开的url
     * @param showParams  页面打开方式自定义参数
     * @param taokeParams 淘客参数
     * @param trackParams 链路跟踪参数（自定义）
     * @param result
     */
    public void openByUrl(
            String detailUrl,
            Map<String, String> showParams,
            Map<String, Object> taokeParams,
            Map<String, String> trackParams,
            final MethodChannel.Result result) {

        AlibcTrade.openByUrl(
                context,
                detailUrl,
                mapToAlibcShowParams(showParams),
                mapToAlibcTaokeParams(taokeParams),
                trackParams,
                new AlibcTradeCallback() {
                    @Override
                    public void onSuccess(int i) {
                        Map map = new HashMap();
                        map.put("status", true);
                        map.put("code", i);
                        map.put("msg", "打开成功");
                        result.success(map);
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Map map = new HashMap();
                        map.put("status", false);
                        map.put("msg", s);
                        map.put("code", i);
                        result.success(map);
                    }
                });
    }

    /**
     * 媒体外跳页面路由协议
     */
    public void registerNavigateUrl() {
        AlibcNavigateCenter.registerNavigateUrl(new AlibcNavigateCenter.IUrlNavigate() {

            @Override
            public boolean openUrl(Context context, final String s) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        channel.invokeMethod("registerNavigateUrl", s);
                    }
                });
                return true;
            }
        });
    }

    /**
     * 注册相关图片库协议
     */
    public void registerImage() {
        AlibcImageCenter.registerImage(new ImageImpl());
    }


    private AlibcShowParams mapToAlibcShowParams(Map<String, String> map) {
        AlibcShowParams params = new AlibcShowParams();

        if (mapContainsKey(map, "backUrl")) {
            params.setBackUrl(map.get("backUrl"));
        }
        if (mapContainsKey(map, "degradeUrl")) {
            params.setDegradeUrl(map.get("degradeUrl"));
        }
        if (mapContainsKey(map, "title")) {
            params.setTitle(map.get("title"));
        }
        if (mapContainsKey(map, "clientType")) {
            if ("1".equals(map.get("clientType"))) {
                params.setClientType("tmall");
            } else {
                params.setClientType("taobao");
            }
        }

        if (mapContainsKey(map, "degradeType")) {
            if ("0".equals(map.get("degradeType"))) {
                params.setDegradeType(AlibcDegradeType.H5);
            } else if ("1".equals(map.get("degradeType"))) {
                params.setDegradeType(AlibcDegradeType.Download);
            }
        }

        if (mapContainsKey(map, "openType")) {
            if ("0".equals(map.get("openType"))) {
                params.setOpenType(OpenType.Auto);
            } else if ("1".equals(map.get("openType"))) {
                params.setOpenType(OpenType.Native);
            }
        }

        return params;
    }


    private AlibcBizParams mapToAlibcBizParams(Map<String, Object> map) {
        AlibcBizParams params = new AlibcBizParams();

        if (mapContainsKey(map, "id")) {
            params.setId((String) map.get("id"));
        }
        if (mapContainsKey(map, "shopId")) {
            params.setShopId((String) map.get("shopId"));
        }
        if (mapContainsKey(map, "sellerId")) {
            params.setSellerId((String) map.get("sellerId"));
        }

        if (mapContainsKey(map, "extParams")) {
            params.setExtParams((Map) map.get("extParams"));
        }

        return params;
    }


    private AlibcTaokeParams mapToAlibcTaokeParams(Map<String, Object> map) {
        String pid = "";
        if (mapContainsKey(map, "pid")) {
            pid = (String) map.get("pid");
        }
        AlibcTaokeParams params = new AlibcTaokeParams(pid);
        if (mapContainsKey(map, "subPid")) {
            params.subPid = (String) map.get("subPid");
        }
        if (mapContainsKey(map, "unionId")) {
            params.unionId = (String) map.get("unionId");
        }
        if (mapContainsKey(map, "relationId")) {
            params.relationId = (String) map.get("relationId");
        }
        if (mapContainsKey(map, "materialSourceUrl")) {
            params.materialSourceUrl = (String) map.get("materialSourceUrl");
        }

        if (mapContainsKey(map, "extParams")) {
            params.extParams = (Map) map.get("extParams");
        }


        return params;
    }

    private boolean mapContainsKey(Map map, String key) {
        return map != null && map.containsKey(key) && map.get(key) != null;
    }


}
